# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://rui.hzzmdz.com/pay/payment'
_QUERY_GATEWAY = 'http://apitest.hzzmdz.com/pay/payquery'

APP_CONF = {
    '18022612530301': {  # witch 支付方式和单笔限额：qqwap(0---1000),京东wap(0---5000),快捷（0----10000）
        'API_KEY': '4ab9521b262ce359be70fca834f59f57',
        'gateway': 'https://ebank.baishengpay.com/Payment/Gateway',
        'query_gateway': 'https://ebank.baishengpay.com/Payment/PaymentQuery',
    },
    '18022610331701': {  # dwc
        'API_KEY': '9f719d59afc483294a9379de1dce3443',
        'gateway': 'https://ebank.baishengpay.com/Payment/Gateway',
        'query_gateway': 'https://ebank.baishengpay.com/Payment/PaymentQuery',
    },
    '18022612582701': {  # loki
        'API_KEY': 'abbd2213bab1b0f7ca2e7930dfd28162',
        'gateway': 'https://ebank.baishengpay.com/Payment/Gateway',
        'query_gateway': 'https://ebank.baishengpay.com/Payment/PaymentQuery',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s = s[0:len(s) - 1]
    s += key
    _LOGGER.info("baishengpay sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['Sign']
    params.pop('Sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("baishengpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 1	ALIPAY_QRCODE_PAY	支付宝扫码
# 2	ALIPAY_WAP_PAY	支付宝WAP
# 3	QQ_QRCODE_PAY	QQ扫码
# 4	QQ_WAP_PAY	QQWAP
# 5	WECHAT_QRCODE_PAY	微信扫码
# 6	WECHAT_WAP_PAY	微信WAP
# 7	UNIONPAY_QRCODE_PAY	银联扫码
# 8	UNIONPAY_WAP_PAY	银联WAP
# 9	JD_QRCODE_PAY	京东扫码
# 10	JD_WAP_PAY	京东WAP
# 11	BD_QRCODE_PAY	百度扫码
# 12	BD_WAP_PAY	百度WAP
# 13	SN_QRCODE_PAY	苏宁扫码
# 14	SN_WAP_PAY	苏宁WAP
# 15	MT_QRCODE_PAY	美团扫码
# 16	MT_WAP_PAY	美团WAP
# 17	ONLINE_BANK_PAY	网银支付
# 18	ONLINE_BANK_QUICK_PAY	网银快捷
def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'WECHAT_WAP_PAY'
    elif service == 'alipay':
        payType = 'ALIPAY_WAP_PAY'
    elif service == 'qq':
        payType = 'QQ_WAP_PAY'
    elif service == 'quick':
        payType = 'ONLINE_BANK_QUICK_PAY'
    else:
        payType = 'JD_WAP_PAY'
    return payType


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('MerchantId', app_id),
        ('Timestamp', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())),
        ('PaymentTypeCode', _get_pay_type(service)),
        ('OutPaymentNo', str(pay.id)),
        ('PaymentAmount', str(int(pay_amount * 100))),
        ('NotifyUrl', '{}/pay/api/{}/baishengpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('PassbackParams', '213123123123'),
    ))
    parameter_dict['Sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("baishengpay create: %s", parameter_dict)
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("baishengpay notify body: %s", request.body)
    data = dict(request.POST.iteritems())
    _LOGGER.info("baishengpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['OutPaymentNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('baishengpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['PaymentState'])
    trade_no = data['PaymentNo']
    total_fee = float(data['PaymentAmount']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'S':
        _LOGGER.info('baishengpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('MerchantId', app_id),
        ('Timestamp', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())),
        ('OutPaymentNo', str(pay_order.id)),
    ))
    parameter_dict['Sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('baishengpay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info('baishengpay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['PaymentState'])
        total_fee = float(data['PaymentAmount']) / 100.0
        trade_no = data['PaymentNo']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # 入款状态（W - 待入款，S - 入款成功）
        if trade_status == 'S':
            _LOGGER.info('baishengpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
